import axios from "axios"
import forge from "node-forge"

// AES-GCM 的 key（示例，必须是 16/24/32字节）
const secretKeyStr = "MIIBSwIBADCCASsG" // 32字节示例

// 这里不再使用 Web Crypto API，而直接使用 forge
function getCryptoKey() {
  // forge AES密钥直接是一个字节串
  return forge.util.createBuffer(forge.util.encodeUtf8(secretKeyStr.slice(0, 32))).getBytes()
}

const userInfo = JSON.parse((sessionStorage.getItem("userInfo")))
// console.log(userInfo?.userId  '11111');

// const ticketReq = axios.create({
  // headers: {
  //   userId: userInfo?.userId,
  //   Accept: '*/*',
	// 	"Content-Type": "application/json;charset=UTF-8"
  // },
//   timeout: 30000 // 请求超时时间
// })

// 封装好的 http 请求
export async function httppost(params) {
  console.log(params.JSONStr)
  const JSONStr = JSON.stringify(params.JSONStr)
  const encryptedData = await Encrypt(JSONStr)
  // 组装URL参数（这里直接使用Base64编码）
  const formData = encodeURIComponent(encryptedData)

  return axios
    .post("http://8.155.50.173:29190/api/rvic/ic-sharedstation"+params.URL, `jsonstr=${formData}`)
    .then(async (res) => {
      if (res.data === "驿站没有授权，请联系管理员") {
        localStorage.setItem("moreRouteList", [])
        localStorage.setItem("routeList", [])
        return
      }
      if (res.data.resultCode === "1" && res.data.resultMessage === "SUCCESS") {
        // 先解密
        const decrypted = await Decrypt(res.data.data)
        res.data.data = JSON.parse(decrypted)
        console.log(res.data,'back');
        return res.data
      } else {
        return res.data
      }
    })
}

// 加密
export async function Encrypt(plaintext) {
  const key = getCryptoKey()

  // 12字节IV
  const iv = forge.random.getBytesSync(12)

  const cipher = forge.cipher.createCipher("AES-GCM", key)
  cipher.start({
    iv: iv,
    tagLength: 128 // 16字节
  })
  cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(plaintext)))
  const success = cipher.finish()

  if (!success) {
    throw new Error("加密失败！")
  }

  const ciphertext = cipher.output.getBytes() // 密文
  const tag = cipher.mode.tag.getBytes() // 16字节Tag

  // 拼接iv+ciphertext+tag
  const combined = forge.util.createBuffer()
  combined.putBytes(iv)
  combined.putBytes(ciphertext)
  combined.putBytes(tag)

  // 转Base64
  return forge.util.encode64(combined.getBytes())
}

// 解密
export async function Decrypt(base64Ciphertext) {
  const key = getCryptoKey()

  const combinedBytes = forge.util.decode64(base64Ciphertext)

  // 拆分
  const iv = combinedBytes.slice(0, 12)
  const ciphertext = combinedBytes.slice(12, combinedBytes.length - 16)
  const tag = combinedBytes.slice(combinedBytes.length - 16)

  const decipher = forge.cipher.createDecipher("AES-GCM", key)
  decipher.start({
    iv: iv,
    tag: tag
  })
  decipher.update(forge.util.createBuffer(ciphertext))

  const success = decipher.finish()

  if (!success) {
    throw new Error("解密失败！")
  }

  return forge.util.decodeUtf8(decipher.output.getBytes())
}
